#coding=utf-8
from core.error import ServiceError
from .const import APPManager
from . import model
from tornado.httpclient import HTTPRequest

def wx_login_request(js_code,app_key):
    app_info = APPManager.get_app_info(app_key)
    if app_info is None:
        raise ServiceError('error key')
    url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type=authorization_code"
    query_data = {"js_code":js_code}
    query_data.update(app_info)
    return HTTPRequest(url=url.format(**query_data))


def xcx_login(json_data,app_key):
    unionid=json_data.get('unionid')
    open_id = json_data['openid']
    if unionid is None:
        new_user_obj = model.UnionUsers()
        new_user_obj.login_app_key=app_key
        new_user_obj.login_openid=open_id
        new_user_obj.save()
        return new_user_obj
    else:
        user_obj =model.UnionUsers.all_objects().filter(unionid=unionid).select()
        if not user_obj:
            # 查询app_key
            old_user_obj = model.UnionUsers.all_objects().filter(login_app_key=app_key,login_openid=open_id).get()
            if old_user_obj:
                old_user_obj.unionid = unionid
                old_user_obj.save()
                return old_user_obj
            else:
                new_user_obj = model.UnionUsers()
                new_user_obj.unionid = unionid
                new_user_obj.save()
                return new_user_obj
        else:
            #有多条记录
            return user_obj[0]



